<?php
namespace app\manage\controller;

use app\manage\controller\BaseController;
use think\facade\Db;
use think\facade\View;
use app\manage\model\Shuoming as Shuomingmodel;

class Shuoming extends BaseController
{
    public function index()
    {
        $data=input('get.');
        if(!isset($data['key'])){
            $data['key']='';
        }
        View::assign('data', $data);
        $info=Shuomingmodel::where('title', 'like', '%'.$data['key'].'%')
        ->order('id desc')
        ->paginate(10,false,['query'=>request()->param()]);

        View::assign('info', $info);
        View::assign('count1', $info->total());
        return View::fetch();
    }
    public function ajax()
    {
        $data=input('post.');
        $shuoming=new Shuomingmodel();
        if ($data['type']=='shuoming_del') {
            if ($shuoming->destroy($data['id'])) {
                return json(['code' => 1, 'message' => '操作成功']);
            } else {
                return json(['code' => 0, 'message' => '操作失败']);
            }
        }
        if ($data['type']=='shuoming_all') {
            if ($shuoming->destroy($data['id'])) {
                return json(['code' => 1, 'message' => '操作成功']);
            } else {
                return json(['code' => 0, 'message' => '操作失败']);
            }
        }
		if($data['type']=='shuoming_start'){
			if($shuoming->where('id',$data['id'])->update(['isopen'=>1])){
                return json(['code' => 1, 'message' => '操作成功']);
            } else {
                return json(['code' => 0, 'message' => '操作失败']);
            }
		}
		if($data['type']=='shuoming_stop'){
			if($shuoming->where('id',$data['id'])->update(['isopen'=>0])){
                return json(['code' => 1, 'message' => '操作成功']);
            } else {
                return json(['code' => 0, 'message' => '操作失败']);
            }
		}
        return json(['code' => 0, 'message' => '失败']);
    }
    public function add()
    {
        if (request()->isPost()) {
            $data=input('post.');
            $validate = new \app\manage\validate\Shuoming;
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }
			
            if (!isset($data['is_tui'])) {
                $data['is_tui']=0;
            } else {
                $data['is_tui']=1;
            }
            if ($data['create_time']) {
                $data['create_time']=strtotime($data['create_time']);
            }else{
                unset($data['create_time']);
            }
            $file = request()->file('');
            if (isset($file['pic'])) {
                try {
                    validate(['pic'=>'fileSize:5242880|fileExt:jpg,png,gif,webp,jpeg'])->check($file);
                    $info=\think\facade\Filesystem::disk('public')->putFile("shuoming", $file['pic']);
                    $data['pic']='/storage/'.strtr($info, " \ ", " / ");
                } catch (\think\exception\ValidateException $e) {
                    $this->error($e->getMessage());
                }
            } else {
                if (isset($data['ti'])) {
                    preg_match_all("/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png]))[\'|\"].*?[\/]?>/", $data["text"], $arr);
					$config=Db::name('config')->column('value', 'key');
					//压缩图片
					foreach ($arr[1] as $k=>$v) {
					    if (substr($v, 0, 4)!='http' and substr($v, 0, 2)!='//' and is_file(substr($v, 1))) {
					        $newarr=getimagesize(substr($v, 1));
						   if ($config["is_ya"] ==1 and $newarr[0] >$config["ya_w"]) {
						      $image = \think\Image::open(substr($v, 1));
						      $h=$config["ya_w"]*$newarr[1]/$newarr[0];
						      $image->thumb($config['ya_w'],$h)->save(substr($v, 1));
						   }
					    }
					}
                    foreach ($arr[1] as $k=>$v) {
                        if (substr($v, 0, 4)!='http' and substr($v, 0, 2)!='//' and is_file(substr($v, 1))) {
                            $newarr=getimagesize(substr($v, 1));
                            if ($newarr[0] >100 and $newarr[1] >100) {
                                //图片转移位置
                                if (!is_dir("storage/shuoming/".date("Ymd"))) {
                                    mkdir("storage/shuoming/".date("Ymd"),0777,true);
                                }
                                $newwei="storage/shuoming/".date("Ymd").'/'.basename(substr($v, 1));
                                $wo=copy(substr($v, 1), $newwei);
                                if ($wo) {
                                    $data['pic']='/'.$newwei;
                                }
                                break;
                            }
                        }
                    }
                }
            }
            
            $config=Db::name('config')->column('value', 'key');
            //设置缩率图
            if ($config['thumbnail']==1 and isset($data['pic'])) {
                if (isset($data['pic'])) {
                    $image = \think\Image::open(substr($data['pic'], 1));
                    //计算配置项
                    if (!$config['t_w']) {
                        $config['t_w']=300;
                    }
                    if (!$config['t_h']) {
                        $config['t_h']=$config['t_w'];
                    }
                    $image->thumb($config['t_w'], $config['t_h'])->save(substr($data['pic'], 1));
                }
            }
            //添加水印
            if ($config['watermark']==1) {
                preg_match_all("/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png]))[\'|\"].*?[\/]?>/", $data["text"], $arr1);
                foreach ($arr1[1] as $k=>$v) {
                    if (substr($v, 0, 4)!='http' and substr($v, 0, 2)!='//') {
                        $image = \think\Image::open(substr($v, 1));
                        $image->text($config['shui_neirong'], dirname(__FILE__).'/FZXBSJW.TTF', $config['shui_zihao'], $config['shui_yanse'], $config['shui_weizhi'], -15)->save(substr($v, 1));
                    }
                }
            }
            if (input('desc')=='') {
                $data['desc']=mb_substr(preg_replace('/\&nbsp;/', '', strip_tags(input('text'))), 0, 200);
            }
            $data['faid']=session('uid');
            if (Shuomingmodel::create($data)) {
                return '<script>alert("你好，添加成功了！");parent.location.reload()</script>';
            } else {
                $this->error('添加失败了');
            }
        }
        return View::fetch();
    }
    public function edit()
    {
        if (request()->isPost()) {
            $data=input('post.');
            $validate = new \app\manage\validate\Shuoming;
            if (!$validate->scene('edit')->check($data)) {
                $this->error($validate->getError());
            }
            if (!isset($data['is_tui'])) {
                $data['is_tui']=0;
            } else {
                $data['is_tui']=1;
            }
            if ($data['create_time']) {
                $data['create_time']=strtotime($data['create_time']);
            }else{
                unset($data['create_time']);
            }
            if (input('desc')=='') {
                $data['desc']=mb_substr(preg_replace('/\&nbsp;/', '', strip_tags(input('text'))), 0, 200);
            }
            $file = request()->file('');
            if (isset($file['pic'])) {
                try {
                    validate(['pic'=>'fileSize:5242880|fileExt:jpg,png,gif,webp,jpeg'])->check($file);
                    $info=\think\facade\Filesystem::disk('public')->putFile("shuoming", $file['pic']);
                    $data['pic']='/storage/'.strtr($info, " \ ", " / ");
                } catch (\think\exception\ValidateException $e) {
                    $this->error($e->getMessage());
                }
            } else {
                if (isset($data['ti'])) {
                    preg_match_all("/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png]))[\'|\"].*?[\/]?>/", $data["text"], $arr);
                    foreach ($arr[1] as $k=>$v) {
                        if (substr($v, 0, 4)!='http' and substr($v, 0, 2)!='//' and is_file(substr($v, 1))) {
                            $newarr=getimagesize(substr($v, 1));
                            if ($newarr[0] >100 and $newarr[1] >100) {
                                //图片转移位置
                                if (!is_dir("storage/shuoming/".date("Ymd"))) {
                                    mkdir("storage/shuoming/".date("Ymd"));
                                }
                                $newwei="storage/shuoming/".date("Ymd").'/'.basename(substr($v, 1));
                                $wo=copy(substr($v, 1), $newwei);
                                if ($wo) {
                                    $data['pic']='/'.$newwei;
                                }
                                break;
                            }
                        }
                    }
                }
            }
            $config=Db::name('config')->column('value', 'key');
			preg_match_all("/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png]))[\'|\"].*?[\/]?>/", $data["text"], $arr);
			foreach ($arr[1] as $k=>$v) {
			    if (substr($v, 0, 4)!='http' and substr($v, 0, 2)!='//' and is_file(substr($v, 1))) {
			        $newarr=getimagesize(substr($v, 1));
				   if ($config["is_ya"] ==1 and $newarr[0] >$config["ya_w"]) {
				      $image = \think\Image::open(substr($v, 1));
				      $h=$config["ya_w"]*$newarr[1]/$newarr[0];
				      $image->thumb($config['ya_w'],$h)->save(substr($v, 1));
				   }
			    }
			}
            //设置缩率图
            if ($config['thumbnail']==1 and isset($data['pic'])) {
                $image = \think\Image::open(substr($data['pic'], 1));
                //计算配置项
                if (!$config['t_w']) {
                    $config['t_w']=300;
                }
                if (!$config['t_h']) {
                    $config['t_h']=$config['t_w'];
                }
                $image->thumb($config['t_w'], $config['t_h'])->save(substr($data['pic'], 1));
            }
            //添加水印
            if ($config['watermark']==1) {
                preg_match_all("/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png]))[\'|\"].*?[\/]?>/", $data["text"], $arr1);
                foreach ($arr1[1] as $k=>$v) {
                    if (substr($v, 0, 4)!='http' and substr($v, 0, 2)!='//') {
                        $image = \think\Image::open(substr($v, 1));
                        $image->text($config['shui_neirong'], dirname(__FILE__).'/FZXBSJW.TTF', $config['shui_zihao'], $config['shui_yanse'], $config['shui_weizhi'], -15)->save(substr($v, 1));
                    }
                }
            }
            $res=Shuomingmodel::update($data, ['id' => input('id')]);
            if ($res) {
                return $this->success('修改成功', url('shuoming/index',['st'=>1]));
            } else {
                return $this->error('修改失败了');
            }
        }
        $cid=input('id',0);
        $data=Db::name('shuoming')->where('id', $cid)->find();
        View::assign('data', $data);
        return View::fetch();
    }
}
